﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BigTestV3.common;
using BigTestV3.xmlHelp;

namespace BigTestV3
{
    public partial class frmStu : Form
    {
        private BasicSetting setting;
        private CurrStu currStu;
        private XmlAnswer xmlAnswer;
        private int x;
        private static int count = 0;

        public frmStu()
        {
            InitializeComponent();

            string settingpath = FilePathTotal.SettingPath;
            string curStu = FilePathTotal.CurrStuPath;
            string answerDetailPath = FilePathTotal.AnswerCheckPath;

            if (File.Exists(settingpath) && File.Exists(curStu) && File.Exists(answerDetailPath))
            {
                setting = XmlHelper.XmlDeserializeFromFile<BasicSetting>(settingpath, Encoding.UTF8);
                currStu = XmlHelper.XmlDeserializeFromFile<CurrStu>(curStu, Encoding.UTF8);
                xmlAnswer = XmlHelper.XmlDeserializeFromFile<XmlAnswer>(answerDetailPath, Encoding.UTF8);
            }

            x = xmlAnswer.TestTime * 60;
        }

        /// <summary>
        /// 加载题目
        /// 在frmStu.Designer.cs中建立委托，Frm_Load()时执行本方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormStuLoad(object sender, EventArgs e)
        {
            string htmpath = FilePathTotal.StudentTestPath;
            if (File.Exists(htmpath))
            {
                wb.ScriptErrorsSuppressed = true;
                wb.Navigate(htmpath);
            }

            if (setting.Ip != null)
            {
                string ip = string.Format(@"tcp://{0}:8085/FileService", setting.Ip);
                _netFileTransferClient.NoticeRegisterMethodName = ip;
            }
            if (_netFileTransferClient.Connect())
            {
                _netFileTransferClient.SendMessage(currStu.Number);
            }
            else
            {
                _netFileTransferClient.Disconnection();
            }
        }

        /// <summary>
        /// 保存答案事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveClick(object sender, EventArgs e)
        {
            SavePapers();
        }

        /// <summary>
        /// 保存答案至本地路径
        /// </summary>
        private void SavePapers()
        {
            #region 注释废代码
            //List<TestDetail> test = new List<TestDetail>();
            //Dictionary<string, string> dicPaperDetailId = GetPaperDetailsId(GetPapersId());
            //foreach (string id in dicPaperDetailId.Keys)
            //{
            //    HtmlElement element = wb.Document.GetElementById("test_" + id);
            //    TestDetail detail = HandlerAnswerFactory.SetAnswerByKinds(id, dicPaperDetailId[id], element);
            //    if (detail != null)
            //    {
            //        test.Add(detail);
            //    }
            //}
            //if (!Directory.Exists(setting.StuPath))
            //{
            //    Directory.CreateDirectory(setting.StuPath);
            //}
            //if (Directory.Exists(setting.StuPath))
            //{
            //    XmlHelper.XmlSerializeToFile(test, setting.StuPath + "\\" + currStu.Number + ".xml", Encoding.UTF8);
            //} 
            #endregion
            List<TestDetail> detailList = new List<TestDetail>();
            string getId = wb.Document.GetElementById("testContentWrap").FirstChild.GetAttribute("Id").ToString();

            int id = Convert.ToInt32(getId.Substring(getId.IndexOf('_') + 1, getId.Length - getId.IndexOf('_') - 1));

            for (int i = 1; i <= id; i++)
            {
                HtmlElement element = wb.Document.GetElementById("test_" + i.ToString());
                string kinds = element.FirstChild.GetAttribute("testtype").ToString().Substring(9).Trim();
                string testlibraryId = element.FirstChild.FirstChild.GetAttribute("testlibraryid").ToString();
                //if (kinds == "K102")
                {
                    TestDetail detail = HandlerAnswerFactory.SetAnswerByKinds(i.ToString(), kinds, testlibraryId, element);

                    if (detail != null)
                    {
                        foreach (AnswerDetail d in xmlAnswer.Answers)
                        {
                            string strScore = "";
                            if (d.AnswerStyle == "R" && d.TestLibraryId.ToString() == detail.TestLibraryId)
                            {
                                if (detail.Answer.Length > 1)
                                {
                                    //d.Answer += "}";
                                    detail.Answer = detail.Answer.Trim().Substring(0, detail.Answer.Trim().LastIndexOf('}'));
                                    string[] stuAns = detail.Answer.Split('}');
                                    string[] sadAns = d.Answer.Trim().Split('}');

                                    for (int j = 0; j < stuAns.Count(); j++)
                                    {
                                        if (stuAns[j] != sadAns[j])
                                        {
                                            d.TotalScore--;
                                            strScore += "0}";
                                        }

                                        else
                                        {
                                            strScore += "1}";
                                        }

                                    }
                                }
                                else
                                {
                                    if (detail.Answer != d.Answer)
                                    {
                                        d.TotalScore--;
                                    }
                                }
                                detail.TotalScores = d.TotalScore;
                                strScore = strScore.Substring(0, strScore.LastIndexOf('}'));
                                detail.Score = strScore;

                            }
                        }
                        detailList.Add(detail);
                    }
                }
            }
            if (!Directory.Exists(setting.StuPath))
            {
                Directory.CreateDirectory(setting.StuPath);
            }
            if (Directory.Exists(setting.StuPath))
            {
                Answer answer = new Answer()
                                    {
                                        List = detailList,
                                        Name = currStu.Name,
                                        StudentNumber = currStu.Number,
                                        StudentId = currStu.StudentId,
                                        TestId = xmlAnswer.TestId.ToString()
                                    };
                //保存至本地文件
                XmlHelper.XmlSerializeToFile(answer, setting.StuPath + "\\" + currStu.Number + ".xml", Encoding.UTF8);
            }

        }

        /// <summary>
        /// 上传答案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadClick(object sender, EventArgs e)
        {
            if (!_netFileTransferClient.Connect())
            {
                _netFileTransferClient.Disconnection();
                MessageBox.Show("无法连接目标！");
            }
            else
            {
                string localPath = setting.StuPath + "\\" + currStu.Number + ".xml";
                string serverPath = setting.TecPath + "\\" + currStu.Number + ".xml";

                //_netFileTransferClient.SendMessage(currStu.Number);
                if (File.Exists(localPath))
                {

                    _netFileTransferClient.SendFile(localPath, serverPath);
                    MessageBox.Show("上传成功");
                }
                else
                {
                    MessageBox.Show("文件不存在，可能是您尚未保存试卷");
                }
            }
            _netFileTransferClient.Disconnection();
        }

        #region 注释废代码
        ///// <summary>
        ///// 获取试卷的Id
        ///// </summary>
        ///// <returns></returns>
        //private List<int> GetPapersId()
        //{
        //    List<int> list = new List<int>();
        //    for (int i = 1; i < 13; i++)
        //    {
        //        list.Add(i);
        //    }
        //    return list;
        //}

        ///// <summary>
        ///// 获取试卷的Id和class
        ///// </summary>
        ///// <param name="list"></param>
        ///// <returns></returns>
        //private Dictionary<string, string> GetPaperDetailsId(List<int> list)
        //{
        //    Dictionary<string, string> dicPaperDetailId = new Dictionary<string, string>();
        //    foreach (int i in list)
        //    {
        //        string tempclass = wb.Document.GetElementById("test_" + i.ToString()).OuterHtml;
        //        tempclass = tempclass.Substring(tempclass.IndexOf("class=") + 6, 4);
        //        dicPaperDetailId.Add(i.ToString(), tempclass);
        //    }
        //    return dicPaperDetailId;
        //} 
        #endregion

        /// <summary>
        /// 计时器显示剩余时间，到点则自动上传作业并关闭窗体
        /// 定时查找已提交答案的学生的名单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerTick(object sender, EventArgs e)
        {
            if (x >= 0)
            {
                //有个DateTime类可以处理时间情况，不要这么处理
                int h = x / 3600;

                int m = x % 3600 / 60; ;

                int s = x % 60;

                string time = "距离考试结束还有：" + h.ToString() + "小时:" + m.ToString() + "分钟:" + s.ToString() + "秒";

                tsbTime.Text = time;

                x--;
            }
            //时间到，考试结束
            else
            {
                timer.Stop();
                //只有一个选项:OK。用户只能这么选。
                //BUG:用户可以直接关闭对话框，这种情况下面的代码可能不执行！
                if (DialogResult.OK == MessageBox.Show("时间到请停止答卷", "提示信息", MessageBoxButtons.OK))
                {
                    tsbSave.Enabled = false;
                    tsbUpload.Enabled = false;

                    SavePapers();

                    string localPath = setting.StuPath + "\\" + currStu.Number + ".xml";
                    string serverPath = setting.TecPath + "\\" + currStu.Number + ".xml";
                    if (File.Exists(localPath))
                    {
                        _netFileTransferClient.SendFile(localPath, serverPath);
                        MessageBox.Show("上传成功");
                    }
                    else
                    {
                        MessageBox.Show("文件不存在，可能是您尚未保存试卷");
                    }
                }
            }

        }

        /// <summary>
        /// 播放考试MP3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaEnter(object sender, EventArgs e)
        {
            if (count < 1)
            {
                WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
                wplayer.URL = FilePathTotal.Mp3Path;
                wplayer.controls.play();
                count++;
            }
        }

    }
}

